package Arrays;

/**
 * 作者:hfj
 * 功能:191.位1的个数
 * 日期: 2025/10/23 10:54
 */
public class HammingWeight {
    public static void main(String[] args) {
        int n = 2147483645;
        System.out.println(hammingWeight(n));
    }


    public static int hammingWeight1(int n) {
        //采用取余统计1的个数
        String temp = "";
        int l,res = 0;
        while (n > 0){
            l = n % 2;
            temp += l;
            n /= 2;
        }
        for (int i = 0; i < temp.length(); i++) {
            if (temp.charAt(i) == '1'){
                res++;
            }
        }
        return res;
    }

    /** 函数底层代码
     * public static int bitCount(int i) {
     *         // HD, Figure 5-2
     *         i = i - ((i >>> 1) & 0x55555555);
     *         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
     *         i = (i + (i >>> 4)) & 0x0f0f0f0f;
     *         i = i + (i >>> 8);
     *         i = i + (i >>> 16);
     *         return i & 0x3f;
     *     }
     * */
    public static int hammingWeight(int n){
        return Integer.bitCount(n);
    }
}
